package com.hsy.order.common.ui

import android.annotation.SuppressLint
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.flux.utils.LogUtil

import com.hsy.order.R
import com.hsy.order.base.action.RequestCode
import com.hsy.order.base.ui.activity.BaseActivityWithToolbar
import com.hsy.order.common.service.OrderService
import com.hsy.order.order.ui.OrderFragment
import com.hsy.order.common.store.MainStore
import com.hsy.order.setting.ui.SettingFragment
import com.hsy.order.order.data.OrderData
import com.hsy.order.setting.ui.PrintersActivity
import com.hsy.order.utils.BluetoothPrintFormatUtil
import com.hsy.order.utils.CommonUtils
import com.tencent.android.tpush.XGIOperateCallback
import com.tencent.android.tpush.XGPushManager
import com.zj.btsdk.BluetoothService

import kotlinx.android.synthetic.main.activity_main.*
import java.util.*

/**
 * 主Activity
 * Created on 2018/3/26.
 *
 * @author yang
 */
class MainActivity : BaseActivityWithToolbar<MainStore>() {

    /**
     * 数据缓存器
     */
    override var store = MainStore(dispatcher)

    /**
     * Tab对应的Fragment
     */
    private val fragments = arrayOf(OrderFragment::class.java, SettingFragment::class.java)
    /**
     * Tab显示的文字*
     */
    private val fragmentsNames = arrayOf("订单", "设置")

    /**
     * 蓝牙设备MAC地址
     */
    private var address = ""

    /**
     * 蓝牙设备是否连接
     */
    private var isConnected = false

    /**
     * 添加TabItem
     * @param index Tab索引
     */
    private fun getTabItem(index: Int): View {
        val view = LayoutInflater.from(this).inflate(R.layout.tab_indicator, null)
        val text: TextView = view.findViewById(R.id.tab_text)
        text.text = fragmentsNames[index]
        return view
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setTitle(R.string.title_order)

        tabs.setup(this, supportFragmentManager, R.id.container)

        for (i in fragments.indices) {
            val tabSpec = tabs.newTabSpec(fragmentsNames[i])
            tabSpec.setIndicator(getTabItem(i))
            tabs.addTab(tabSpec, fragments[i], null)
        }
        tabs.tabWidget.showDividers = LinearLayout.SHOW_DIVIDER_NONE
        tabs.setOnTabChangedListener { tabId ->
            when (tabId) {
                fragmentsNames[0] -> setTitle(R.string.title_order)
                fragmentsNames[1] -> setTitle(R.string.title_setting)
            }
        }
        tabs.currentTab = 0

        address = CommonUtils.getDeviceAddress()
        connectDevice()

        if (CommonUtils.checkLogin()) XGPushManager.bindAccount(this, CommonUtils.getImId(), object : XGIOperateCallback {
            override fun onFail(data: Any?, errCode: Int, msg: String?) {
                LogUtil.i("注册失败，错误码：$errCode，错误信息：$msg")
            }

            override fun onSuccess(data: Any?, flag: Int) {
                LogUtil.i("注册成功，设备token为：$data")
            }
        })
        startService(Intent(this, OrderService::class.java))

        val versionCode = packageManager.getPackageInfo(packageName, 0).versionCode
        if (versionCode == CommonUtils.getVersionCode()) {
            showToast("本应用需要常驻后台，请在省电设置或者后台管理等设置中将本应用加入白名单或设为不做限制")
            CommonUtils.saveVersionCode(versionCode)
        }

        //检查版本更新
        //        new VersionChecker(this).check();
    }

    private var mService: BluetoothService? = null
    private var mDevice: BluetoothDevice? = null

    /**
     * 初始化蓝牙
     */
    private fun initBluetooth(): Boolean {
        if (mService == null) mService = BluetoothService(this, mHandler)
        if (!mService!!.isAvailable) {
            showToast("您的蓝牙设备目前不可用，请检查蓝牙设置")
            return false
        }
        if (!mService!!.isBTopen) {
            startActivityForResult(Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), RequestCode.BluetoothStart)
            return false
        }
        return true
    }

    private val charsetString = "GBK"

    /**
     * 打印小票
     */
    fun onPrint(data: OrderData) {
        if (isConnected) {
            for (i in 0 until CommonUtils.getPrintNum()) {
                mService!!.write(BluetoothPrintFormatUtil.RESET)
                mService!!.sendMessage("\n", charsetString)
                mService!!.write(BluetoothPrintFormatUtil.DOUBLE_HEIGHT_WIDTH)
                //打印订单号-
                val id = if (data.order_sn.length >= 13) data.order_sn.substring(0, 1) + data.order_sn.substring(7) else data.order_sn
                mService!!.sendMessage(BluetoothPrintFormatUtil.printCenter("#$id", true), charsetString)
                //打印订单状态
                val type = when (data.type) {
                    "1" -> "堂食订单"
                    "2" -> "自取订单"
                    else -> "外卖订单"
                }
                mService!!.sendMessage(BluetoothPrintFormatUtil.printCenter(type, true), charsetString)
                //打印客户信息
                mService!!.write(BluetoothPrintFormatUtil.NORMAL)
                mService!!.sendMessage(BluetoothPrintFormatUtil.printSeparator(), charsetString)
                val customer = ("下单时间：${data.create_datetime_str}\n" + "客户电话：${data.phone}")
                mService!!.sendMessage(customer, charsetString)
                //打印送餐地址
                if (data.address != "") mService!!.sendMessage("送餐地址：${data.address}${data.door}", charsetString)
                //打印分割线
                mService!!.sendMessage(BluetoothPrintFormatUtil.printSeparator(), charsetString)
                //打印菜品
                val map = LinkedHashMap<String, LinkedList<String>>()
                val list = LinkedList<String>()
                for (food in data.goods) {
                    list.add("${food.name}\$x${food.qty}$${food.qty.toInt() * food.price.toFloat()}")//编码格式：菜品$x数量$总钱数
                }
                map[""] = list
                val menu = BluetoothPrintFormatUtil.printMenuMSG(map)
                mService!!.sendMessage(menu, charsetString)
                //打印其他费用
                val other = ArrayList<String>()
                if (data.boxfee != "0.00") other.add("餐盒费：$${data.boxfee}")
                if (data.coupon != "0.00") other.add("红包优惠：$-${data.coupon}")
                if (data.freight != "0.00") other.add("配送费：$${data.freight}")
                if (other.size != 0) {
                    mService!!.sendMessage(BluetoothPrintFormatUtil.printCenterWithSeparator("其他费用"), charsetString)
                    mService!!.sendMessage(BluetoothPrintFormatUtil.printTwoRow(other, false), charsetString)
                }
                //打印分割线
                mService!!.sendMessage(BluetoothPrintFormatUtil.printSeparator(), charsetString)
                //打印实付金额
                val money = ArrayList<String>()
                money.add("实付：$${data.amount}")
                mService!!.write(BluetoothPrintFormatUtil.DOUBLE_HEIGHT_WIDTH)
                mService!!.sendMessage(BluetoothPrintFormatUtil.printTwoRow(money, true), charsetString)
                mService!!.write(BluetoothPrintFormatUtil.NORMAL)
                //打印备注
                if (data.remark != "") {
                    mService!!.sendMessage(BluetoothPrintFormatUtil.printSeparator(), charsetString)
                    mService!!.sendMessage("备注：", charsetString)
                    mService!!.sendMessage(data.remark, charsetString)
                }
                mService!!.sendMessage("\n\n", charsetString)
            }
            //打印订单完分割线
            mService!!.sendMessage(BluetoothPrintFormatUtil.printCenterWithSeparator("#${data.order_sn}订单完"), charsetString)
            mService!!.sendMessage("\n\n", charsetString)
        } else {
            showToast("正在尝试连接蓝牙打印机，请稍后再打印")
            connectDevice()
        }
    }

    /**
     * 设置要连接的蓝牙设备
     */
    fun setBluetooth() {
        if (initBluetooth()) startActivityForResult(PrintersActivity::class.java, RequestCode.BluetoothConnect)
    }

    /**
     * 连接蓝牙设备
     */
    private fun connectDevice() {
        if (initBluetooth()) {
            if (address != "") {
                mDevice = mService!!.getDevByMac(address)
                mService!!.connect(mDevice)
                CommonUtils.showProgressDialog(this)
            } else showToast("您还未设置蓝牙打印机")
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
        //请求打开蓝牙
            RequestCode.BluetoothStart -> if (resultCode != Activity.RESULT_OK) showToast("您已拒绝打开蓝牙")
        //请求连接某一蓝牙设备
            RequestCode.BluetoothConnect -> if (resultCode == Activity.RESULT_OK) {   //已点击搜索列表中的某个设备项
                address = data!!.extras!!.getString(PrintersActivity.EXTRA_DEVICE_ADDRESS)  //获取列表项中设备的mac地址
                connectDevice()
            }
        }
    }

    /**
     * 创建一个Handler实例，用于接收BluetoothService类返回回来的消息
     */
    @SuppressLint("HandlerLeak")
    private val mHandler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
            //蓝牙连接状态变化
                BluetoothService.MESSAGE_STATE_CHANGE -> when (msg.arg1) {
                //已连接
                    BluetoothService.STATE_CONNECTED -> {
                        CommonUtils.saveDeviceAddress(address)
                        CommonUtils.hideProgressDialog()
                        showToast("蓝牙设备连接成功")
                        isConnected = true
                    }
                //正在连接
                    BluetoothService.STATE_CONNECTING -> LogUtil.i("蓝牙调试", "正在连接.....")
                //监听连接的到来
                    BluetoothService.STATE_LISTEN, BluetoothService.STATE_NONE -> LogUtil.i("蓝牙调试", "等待连接.....")
                }
            //蓝牙已断开连接
                BluetoothService.MESSAGE_CONNECTION_LOST -> {
                    CommonUtils.hideProgressDialog()
                    showToast("蓝牙设备失去连接")
                    isConnected = false
                }
            //无法连接设备
                BluetoothService.MESSAGE_UNABLE_CONNECT -> {
                    CommonUtils.hideProgressDialog()
                    showToast("蓝牙设备无法连接")
                    isConnected = false
                }
            }
        }
    }

    private var isExit = false

    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        if (KeyEvent.ACTION_UP == event.action && KeyEvent.KEYCODE_BACK == event.keyCode) {
            exit()
            return true
        }
        return super.dispatchKeyEvent(event)
    }

    public override fun handleMessage(msg: Message) {
        super.handleMessage(msg)
        isExit = false
    }

    /**
     * 退出事件
     */
    private fun exit() {
        if (!isExit) {
            isExit = true
            showToast(R.string.msg_exit)
            // 利用handler延迟发送更改状态信息
            sendEmptyMessageDelayed(0, 2000)
        } else finish()
    }

    /**
     * 设置不显示顶部返回按钮
     */
    override fun setNavigationIcon() = true
}